//
//  AddLoanViewController.m
//  Wallets Manager
//
//  Created by Tung Nguyen on 10/14/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "AddLoanViewController.h"

@interface AddLoanViewController () {
    NSDate *currentDate;
    NSDate *currentDueDate;
    BOOL dateTextFieldSelected;
    BOOL dueDateTextFieldSelected;
}

@end

@implementation AddLoanViewController
@synthesize loanNameTextField;
@synthesize borrowerTextField;
@synthesize amountTextField;
@synthesize walletNameTextField;
@synthesize dateTextField;
@synthesize dueDateTextField;
@synthesize noteTextField;
@synthesize dateString;
@synthesize pickerDateViewPopup;
@synthesize pickerDueDateViewPopup;
@synthesize dateMonthViewCalendar;
@synthesize dueDateMonthViewCalendar;
@synthesize kindOfView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //-----------------Init form set name of Wallet & let user can't change it---------------
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    walletNameTextField.text = delegate.currentWallet.w_name;
    walletNameTextField.enabled = NO;
    
    dateTextFieldSelected = NO;
    dueDateTextFieldSelected = NO;
    
    //-----------------Set form to edit if from Edit---------------
    if([kindOfView isEqualToString:@"Edit"]) {
    
    }
}

- (void)viewDidUnload
{
    [self setBorrowerTextField:nil];
    [self setAmountTextField:nil];
    [self setWalletNameTextField:nil];
    [self setDateTextField:nil];
    [self setDueDateTextField:nil];
    [self setNoteTextField:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)backButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - IBAction Delegate

- (IBAction)addButtonPressed:(id)sender {
    folyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSLog(@"KODAK | Add LOAN");
    if ([kindOfView isEqualToString:@"Add"]) {
        [DataBaseAccess createLoanWithName:loanNameTextField.text andAmount:[amountTextField.text doubleValue] andDate:currentDate andExpectedDate:currentDueDate andBorrower:borrowerTextField.text andNotes:noteTextField.text inWallet:delegate.currentWallet];
    } else {
        
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Text Field Delegate
-(void) textFieldDidBeginEditing:(UITextField *)textField {
    if( textField == dateTextField) {
        dateTextFieldSelected = YES;
        [self createDatePickerView];
    } else if (textField == dueDateTextField) {
        if (currentDate == nil) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"You have choose Date before choose Due Date" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [dueDateTextField resignFirstResponder];
            return;
        }
        dueDateTextFieldSelected = YES;
        [self createDueDatePickerView];
    }
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Month Calendar
- (void) createDatePickerView {
    
    if(pickerDateViewPopup == nil)
    {
        pickerDateViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        
        [pickerDateViewPopup setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
        
        UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        pickerToolbar.barStyle = UIBarStyleBlackOpaque;
        [pickerToolbar sizeToFit];
        
        NSMutableArray *barItems = [[NSMutableArray alloc] init];
        
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
        [barItems addObject:doneBtn];
        
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        [barItems addObject:flexSpace];
        
        UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
        [barItems addObject:cancelBtn];
        
        [pickerToolbar setItems:barItems animated:YES];
        
        if(dateMonthViewCalendar == nil)
        {
            dateMonthViewCalendar = [[TKCalendarMonthView alloc] initWithSundayAsFirst:NO];
            dateMonthViewCalendar.delegate  = self;
            dateMonthViewCalendar.dataSource = self;
            //NSLog(@"MONTH %f x %f", monthViewCalendar.bounds.size.width, monthViewCalendar.bounds.size.height);
            [dateMonthViewCalendar reload];
        }
        [dateMonthViewCalendar setFrame:CGRectMake(0, 44, 320, dateMonthViewCalendar.bounds.size.height)];
        pickerDateViewPopup.clipsToBounds=YES;
        
        //[pickerViewPopup addSubview:datePickerView];
        
        [pickerDateViewPopup addSubview:pickerToolbar];
        [pickerDateViewPopup addSubview:dateMonthViewCalendar];
        [pickerDateViewPopup setBounds:CGRectMake(0, 0, 320, 460)];
        [pickerDateViewPopup showInView:self.view];
        [self popUpDateRefreshFrame];
    } else {
        [pickerDateViewPopup showInView:self.view];
        [self popUpDateRefreshFrame];
    }
}

-(void)popUpDateRefreshFrame
{
    [UIView beginAnimations:@"resize_animation" context:NULL];
    [UIView setAnimationDuration:0.3];
    
    pickerDateViewPopup.clipsToBounds=YES;
    [pickerDateViewPopup setFrame:CGRectMake(0.0, 460 - dateMonthViewCalendar.bounds.size.height - 44, 320, dateMonthViewCalendar.bounds.size.height + 44)];
    
    [UIView commitAnimations];
    
    
}

- (void) createDueDatePickerView {
    
    if(pickerDueDateViewPopup == nil)
    {
        pickerDueDateViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        
        [pickerDueDateViewPopup setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
        
        UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        pickerToolbar.barStyle = UIBarStyleBlackOpaque;
        [pickerToolbar sizeToFit];
        
        NSMutableArray *barItems = [[NSMutableArray alloc] init];
        
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
        [barItems addObject:doneBtn];
        
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        [barItems addObject:flexSpace];
        
        UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
        [barItems addObject:cancelBtn];
        
        [pickerToolbar setItems:barItems animated:YES];
        
        if(dueDateMonthViewCalendar == nil)
        {
            dueDateMonthViewCalendar = [[TKCalendarMonthView alloc] initWithSundayAsFirst:NO];
            dueDateMonthViewCalendar.delegate  = self;
            dueDateMonthViewCalendar.dataSource = self;
            //NSLog(@"MONTH %f x %f", monthViewCalendar.bounds.size.width, monthViewCalendar.bounds.size.height);
            [dueDateMonthViewCalendar reload];
        }
        [dueDateMonthViewCalendar setFrame:CGRectMake(0, 44, 320, dueDateMonthViewCalendar.bounds.size.height)];
        pickerDueDateViewPopup.clipsToBounds=YES;
        
        //[pickerViewPopup addSubview:datePickerView];
        
        [pickerDueDateViewPopup addSubview:pickerToolbar];
        [pickerDueDateViewPopup addSubview:dueDateMonthViewCalendar];
        [pickerDueDateViewPopup setBounds:CGRectMake(0, 0, 320, 460)];
        [pickerDueDateViewPopup showInView:self.view];
        [self popUpDueDateRefreshFrame];
    } else {
        [pickerDueDateViewPopup showInView:self.view];
        [self popUpDueDateRefreshFrame];
    }
    
}



-(void)popUpDueDateRefreshFrame
{
    [UIView beginAnimations:@"resize_animation" context:NULL];
    [UIView setAnimationDuration:0.3];
    
    pickerDueDateViewPopup.clipsToBounds=YES;
    [pickerDueDateViewPopup setFrame:CGRectMake(0.0, 460 - dueDateMonthViewCalendar.bounds.size.height - 44, 320, dueDateMonthViewCalendar.bounds.size.height + 44)];
    
    [UIView commitAnimations];
    
    
}

- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{
	return nil;
}

-(void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)date
{
    NSLog(@"%@", date);
    if (dateTextFieldSelected) {
        currentDate = date;
    } else if (dueDateTextFieldSelected) {
        currentDueDate = date;
    }
}

- (void) calendarMonthView:(TKCalendarMonthView*)monthView monthDidChange:(NSDate*)month animated:(BOOL)animated
{
    //NSLog(@"FRAME = %f X %f", monthView.frame.size.width , monthView.frame.size.height);
    [self performSelector:@selector(popUpRefreshFrame)];
}

-(void)doneDateButtonPressed:(id)sender{
    //Do something here here with the value selected using [pickerView date] to get that value
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    
    if (dateTextFieldSelected) {
        if ([currentDate compare:currentDueDate] == NSOrderedDescending) {
            [dueDateTextField setText:[dateFormatter stringFromDate:currentDate]];
        }

        [dateTextField setText:[dateFormatter stringFromDate:currentDate]];
        [dateTextField resignFirstResponder];
        [pickerDateViewPopup dismissWithClickedButtonIndex:1 animated:YES];
        dateTextFieldSelected = NO;
    } else if (dueDateTextFieldSelected) {
        if ([currentDate compare:currentDueDate] == NSOrderedDescending) {
            [dueDateTextField resignFirstResponder];
            [pickerDueDateViewPopup dismissWithClickedButtonIndex:1 animated:YES];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"You can't choose Due Date that is ealier than Date" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            return;
        } else {
            [dueDateTextField setText:[dateFormatter stringFromDate:currentDueDate]];
            [dueDateTextField resignFirstResponder];
            [pickerDueDateViewPopup dismissWithClickedButtonIndex:1 animated:YES];
            dueDateTextFieldSelected = NO;
        }        
    }
}

-(void)cancelDateButtonPressed:(id)sender{
    
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    //    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    //    [dateTextField setText:[dateFormatter stringFromDate:datePickerView.date]];
    if (dateTextFieldSelected) {
        [dateTextField resignFirstResponder];
        dateTextFieldSelected = NO;
        [pickerDateViewPopup dismissWithClickedButtonIndex:1 animated:YES];
    } else if (dueDateTextFieldSelected) {
        [dueDateTextField resignFirstResponder];
        dueDateTextFieldSelected = NO;
        [pickerDueDateViewPopup dismissWithClickedButtonIndex:1 animated:YES];
    }
    //[currencyPickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
}

@end
